<template>
  <div class="app-container">
    <!-- 条件查询 v-permission="'user:search'"  -->
    <el-card class="box-card">
      <el-form :inline="true" :model="query" size="mini">
        <el-form-item label="ID" width="120px;">
          <el-input v-model.trim="query.id" clearable placeholder="请输入用户ID"/>
        </el-form-item>
        <el-form-item label="用户名" width="120px;">
          <el-input v-model.trim="query.username" clearable placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model.trim="query.phone" clearable placeholder="请输入电话号码"/>
        </el-form-item>
        <el-form-item label="用户邮箱">
          <el-input v-model.trim="query.email" clearable placeholder="请输入用户邮箱"/>
        </el-form-item>
        <el-form-item label="是否锁定" width="120px;">
          <!-- 帐户状态:(0 正常, 1 禁言，2 锁定 ) -->
          <el-select v-model="query.status" clearable >
            <el-option label="正常" :value="0"/>
            <el-option label="禁言" :value="1"/>
            <el-option label="锁定" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="登录IP">
          <el-input v-model.trim="query.loginIp" clearable placeholder="请输入登录IP"/>
        </el-form-item>
        <el-form-item label="注册IP">
          <el-input v-model.trim="query.registerIp" clearable placeholder="请输入注册IP"/>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="query.begin"
            clearable
            placeholder="开始时间"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="-">
          <el-date-picker
            v-model="query.end"
            clearable
            placeholder="结束时间"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item>
          <el-button v-permission="'user:search'" icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
          <el-button v-permission="'user:search'" icon="el-icon-refresh" @click="reload">重置</el-button>
          <el-button v-permission="'user:add'" icon="el-icon-circle-plus-outline" type="success" @click="openAdd">新增
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 数据列表 -->
    <el-table
      :data="list"
      stripe
      border
      height="600"
      style="width: 100%"
    >
      <el-table-column label="序号" width="70" align="center" fixed="left">
        <template slot-scope="scope">
          <!--  page.current 当前页码；page.size 每页记录数 -->
          {{ (current - 1) * size + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="avatar" label="头像" width="60px" fixed="left">
        <template slot-scope="scope">
          <el-image
            :src="scope.row.avatar"
            :preview-src-list="[scope.row.avatar]"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" prop="username" label="用户名" width="120px" fixed="left"/>
      <el-table-column align="center" prop="phone" label="手机号" width="150px"/>
      <el-table-column align="center" prop="email" label="邮箱" width="200px"/>
      <el-table-column align="center" prop="sign" label="个性签名" width="300px"/>
      <!-- 帐户状态:(0 正常, 1 禁言，2 永久封禁 ) -->
      <el-table-column align="center" prop="status" label="状态" width="80px">
        <!-- (1 可用，0 删除用户) -->
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 0" type="success">正常</el-tag>
          <el-tag v-if="scope.row.status == 1" type="warning">禁言</el-tag>
          <el-tag v-if="scope.row.status == 2" type="danger">锁定</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="lastLoginTime" label="上一次登录时间" width="160px"/>
      <el-table-column align="center" prop="" label="赞赏码" width="80px">
        <template slot-scope="scope">
          <el-image
            :src="scope.row.rewardUrl"
            :preview-src-list="[scope.row.rewardUrl]"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" prop="id" label="ID" width="200px"/>
      <el-table-column align="center" prop="loginIp" label="登录IP" width="180px"/>
      <el-table-column align="center" prop="registerIp" label="注册IP" width="180px"/>
      <el-table-column align="center" prop="pwdUpdateTime" label="密码更新时间" width="160px"/>
      <el-table-column align="center" prop="createTime" label="注册时间" width="160px"/>
      <el-table-column align="center" prop="updateTime" label="更新时间" width="160px"/>
      <el-table-column align="center" label="操作" width="600">
        <template slot-scope="scope">
          <el-button
            v-permission="'user:edit'"
            :disabled="scope.row.status == 1"
            type="warning"
            size="mini"
            @click="forbiddenSpeak(scope.row.id)"
          >禁言
          </el-button>
          <el-button
            v-permission="'user:edit'"
            :disabled="scope.row.status == 2"
            type="info"
            size="mini"
            @click="lock(scope.row.id)"
          >锁定
          </el-button>
          <el-button
            v-permission="'user:edit'"
            :disabled="scope.row.status == 0"
            type="success"
            size="mini"
            @click="handleNormal(scope.row.id)"
          >恢复正常
          </el-button>
          <el-button v-permission="'user:edit'" type="primary" size="mini" @click="handleEdit(scope.row.id)">编辑
          </el-button>
          <el-button v-permission="'user:password'" type="primary" size="mini" @click="handlePwd(scope.row.id)">重置密码
          </el-button>
          <el-button
            v-permission="'user:role'"
            type="primary"
            size="mini"
            @click="handleRole(scope.row.id,scope.row.username)"
          >设置角色
          </el-button>
          <el-button
            v-permission="'user:delete'"
            type="danger"
            size="mini"
            @click="handleDelete(scope.row.id,scope.row.username)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
      align="center"
      background
      :current-page="current"
      :page-sizes="[10, 20,30,50,100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 新增用户子组件 -->
    <add :add-data="addData" :add-visible="addVisible" @closeAddDialog="closeAddDialog" @fetchData="fetchData"/>
    <!-- 编辑用户子组件 -->
    <edit :edit-data="editData" :edit-visible="editVisible" @closeEditDialog="closeEditDialog" @fetchData="fetchData"/>
    <!-- 重置用户密码子组件 -->
    <Pwd
      :pwd-data="pwdData"
      :pwd-visible="pwdVisible"
      @closeUpdatePwdDialog="closeUpdatePwdDialog"
      @fetchData="fetchData"
    />
    <!-- 分配角色子组件 -->
    <el-dialog
      :visible.sync="roleVisible"
      width="65%"
      :before-close="handleCloseRole"
    >
      <h1>给用户 <i class="el-icon-user-solid"/> {{ username }} 分配角色 </h1>
      <!-- roleIds 是当前用户所拥有的角色 ids， saveUserRole 事件是子角色组件触发摬选择的角色 ids -->
      <Role :role-ids="roleIds" :role-visible="roleVisible" :username="username" @saveUserRole="saveUserRole"/>
    </el-dialog>
  </div>
</template>
<script>
import { getList, getById, deleteById, getRoleByUserId, saveUserRole, updateUserStatus } from '@/api/user'
import Add from './add'
import Edit from './edit'
import Pwd from './password'
import Role from '../role'

export default {
  name: 'User',
  components: {
    Add,
    Edit,
    Pwd,
    Role
  },
  data() {
    return {
      list: [],
      current: 1,
      size: 10,
      total: 0,
      query: {},
      // 新增用户
      addData: {},
      addVisible: false,
      // 编辑用户
      editData: {},
      editVisible: false,
      // 重置密码
      pwdData: {
        userId: null
      },
      pwdVisible: false,
      // 分配角色
      roleVisible: false,
      // 传递到子组件中时，至少会传递一个空数组[]，也算有值，只不过是空的（子组件判断是否有 roleIds 值
      roleIds: [], // 封装当前用户所拥有的 角色 ids
      userId: null, // 保存点击分配角色按钮传来的用户ID，保存分配角色用
      username: '' // 分配角色时显示用户名
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      const response = await getList(this.query, this.current, this.size)
      this.list = response.data.records
      this.total = Number(response.data.total)
    },
    // 切换每页显示多少条记录
    handleSizeChange(size) {
      this.size = size
      this.fetchData()
    },
    // 切换当前页码
    handleCurrentChange(current) {
      this.current = current
      this.fetchData()
    },
    // 条件查询
    queryData() {
      this.current = 1
      this.fetchData()
    },
    // 条件查询-重置表单
    reload() {
      this.query = {}
      this.fetchData()
    },
    // 打开新增用户窗口
    openAdd() {
      this.addVisible = true
      this.addData = {}
    },
    // 关闭新增窗口
    closeAddDialog() {
      this.addVisible = false
    },
    // 打开编辑窗口-同时根据ID查询用户详情-回显数据
    async handleEdit(id) {
      const { data } = await getById(id)
      this.editData = data.user
      this.editVisible = true
    },
    // 关闭编辑窗口
    closeEditDialog() {
      this.editVisible = false
      this.editData = {}
    },
    // 打开重置密码窗口
    handlePwd(id) {
      this.pwdVisible = true
      this.pwdData.userId = id
    },
    // 关闭编辑窗口
    closeUpdatePwdDialog() {
      this.pwdVisible = false
      this.pwdData = {}
    },
    // 打开给用户分配角色窗口（传用户ID）
    async handleRole(id, username) {
      this.userId = id
      this.username = username
      const { data } = await getRoleByUserId(id)
      this.roleIds = data.existRoleList
      this.roleVisible = true
    },
    // 关闭角色列表窗口
    handleCloseRole() {
      this.roleVisible = false
    },
    // 角色列表子组件会触发此方法来保存当前用户所选择的角色 ids
    saveUserRole(checkedRoleIds) {
      saveUserRole(this.userId, checkedRoleIds).then(response => {
        if (response.code === 200) {
          this.roleVisible = false
          this.$message.success(response.message)
        } else {
          this.$message.error(response.message)
        }
      })
    },
    // 禁言，将状态值改为 1
    forbiddenSpeak(id) {
      const forbiddenSpeak = '1'
      this.$confirm('确定要将用户 禁言 吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送请求
        updateUserStatus(id, forbiddenSpeak).then(response => {
          if (response.code === 200) {
            this.fetchData()
            this.$message.success('禁言成功')
          } else {
            this.$message.error(response.message)
          }
        })
      }).catch(() => {
      })
    },
    // 锁定用户
    lock(id) {
      const lock = '2'
      this.$confirm('确定要 锁定用户 吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送请求
        updateUserStatus(id, lock).then(response => {
          if (response.code === 200) {
            this.fetchData()
            this.$message.success('锁定用户成功')
          } else {
            this.$message.error(response.message)
          }
        })
      }).catch(() => {
      })
    },
    // 恢复正常，将状态值改为 0 (0 正常, 1 禁言，2 锁定 )'
    handleNormal(id) {
      const normal = '0'
      this.$confirm('确定要将用户状态 恢复正常 吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送请求
        updateUserStatus(id, normal).then(response => {
          if (response.code === 200) {
            this.fetchData()
            this.$message.success('恢复正常成功')
          } else {
            this.$message.error(response.message)
          }
        })
      }).catch(() => {
      })
    },
    // 根据ID删除
    handleDelete(id, username) {
      this.$confirm('确定要删除用户  ' + username + ' 吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送请求
        deleteById(id).then(response => {
          if (response.code === 200) {
            this.fetchData()
            this.$message.success(response.message)
          } else {
            this.$message.error(response.message)
          }
        })
      }).catch(() => {
      })
    }
  }
}
</script>
<style scoped>
.el-image {
  border-radius: 4px;
}

.el-pagination {
  margin: 20px 0 50px;
}

h1 {
  text-align: center;
  margin-bottom: 30px;
}
</style>
